var busid = 0;
var stationid = 0;
var iIntval;
function __generateTable2() {
    return '<table class="table table-bordered table-hover"><thead><tr>' + '<th class="hidden-xs">序號</th><th>車站名</th><th class="hidden-xs">經度</th><th class="hidden-xs">緯度</th><th>操作</th></tr>' + '</thead><tbody>{0}</tbody></table>'
}
function __generateTable3() {
    return '<table class="table table-bordered table-hover"><thead><tr>' + '<th class="hidden-xs">序號</th><th>車站名</th><th class="hidden-xs">經度</th><th class="hidden-xs">緯度</th><th>距離(米)</th><th>操作</th></tr>' + "</thead><tbody>{0}</tbody></table>"
}
var my_pos;
function loadNearStation(data) {
    var i = 0;
    var sb = new StringBuilder();
    for (; i < data.length; i++) {
        var d = data[i];
        sb.append('<tr data-id="{4}" data-code="{5}"><td class="hidden-xs">{0}</td><td>{1}</td><td class="hidden-xs">{2}</td><td class="hidden-xs">{3}</td><td>{6}</td><td><a href="javascript:void(0)">途經線路</a> </td></tr>'.format(i + 1, d.name, d.lng, d.lat, d.id, d.code, Math.floor(distance(d.lat, d.lng, my_pos.lat, my_pos.lng))))
    }
    var t = sb.toString();
    t = __generateTable3().format(t);
    return t
}
function loadStation(data) {
    var i = 0;
    var sb = new StringBuilder();
    for (; i < data.length; i++) {
        var d = data[i];
        sb.append('<tr data-id="{4}" data-code="{5}"><td class="hidden-xs">{0}</td><td>{1}</td><td class="hidden-xs">{2}</td><td class="hidden-xs">{3}</td><td><a href="javascript:void(0)">我在这里</a> </td></tr>'.format(i + 1, d.sName, d.sLng, d.sLat, d.sStationid, d.sCode))
    }
    var t = sb.toString();
    t = __generateTable2().format(t);
    return t
}
function __generateTable1() {
    return '<table class="table table-bordered table-hover"><legend>公交列表</legend><thead><tr>' + '<th>线路名</th><th class="hidden-xs">运营时间</th><th>起点站</th><th>终点站</th><th class="hidden-xs">全程票价</th><th>操作</th></tr>' + "</thead><tbody>{0}</tbody></table>"
}
function loadBus(data) {
    var tips = {
        0 : "下行",
        1 : "上行"
    };
    var sb = new StringBuilder();
    for (var i = 0; i < data.length; i++) {
        var d = data[i];
        var t = "{0} - {1}".format(d.bBeginTime, d.bEndTime);
        var tmp = '<tr data-id="{0}"><td>{1}({6})</td><td class="hidden-xs">{2}</td><td>{3}</td><td>{4}</td><td class="hidden-xs">{5}</td><td><a href="javascript:void(0)">查看所有站点</a></td></tr>';
        sb.append(tmp.format(d.bBusid, d.bLineName, t, d.bStartStation, d.bEndStation, d.bPrice, tips[d.bDir]))
    }
    var t = sb.toString();
    t = __generateTable1().format(t);
    return t
}
function showTips(words) {
    var d = $("div.alert");
    d.text(words);
    d.slideDown(1000,
    function() {
        setTimeout(function() {
            d.slideUp(1000)
        },
        2000)
    })
}
function searchBus() {
    var a = $("#btnList");
    a.parent().siblings().removeClass("active");
    a.parent().addClass("active");
    var alinename = $("input.form-control").val();
    if (alinename.trim() == "") {
        showTips("公交线路的名称不能为空");
        return false
    }
    $.post("index.php/bus/search_by_linename", {
        linename: alinename
    },
    function(r) {
        if (r.ret == 0) {
            bus_show("buslist",
            function(id) {
                $(id).html(loadBus(r.data))
            })
        }
    });
    return false
}
function bodyResize() {
    var h = $("header.navbar").height() + 15;
    $(".main-content").css({
        "margin-top": h + "px"
    })
}
function GetGeo(callback) {
    if (window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(callback)
    } else {
        showTips("你的浏览器不支持获取地理位置")
    }
}
var divArr = ["buslist", "busdetail", "nearstation"];
function bus_show(id, func) {
    clearInterval(iIntval);
    if (func) {
        func("#" + id)
    }
    for (var i = 0; i < divArr.length; i++) {
        if (divArr[i] != id) {
            $("#" + divArr[i]).hide()
        } else {
            $("#" + id).show()
        }
    }
}
function getLineCount(f) {
    $.getJSON("index.php/bus/line_count",
    function(r) {
        if (r.ret == 0) {
            f(r.data)
        } else {
            f(0)
        }
    })
}
function toRad(d) {
    return d * Math.PI / 180
}
function distance(lat1, lng1, lat2, lng2) {
    var dis = 0;
    var radLat1 = toRad(lat1);
    var radLat2 = toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = toRad(lng1) - toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6378137
}
function getLines(p) {
    $.getJSON("index.php/bus/all_bus/" + p,
    function(r) {
        if (r.ret == 0) {
            $("#buslist").html(loadBus(r.data))
        }
    })
}
function loadNearCars(data) {
    
    var b = $("#busdetail div table tbody");
    var sb = new StringBuilder();
    var states = {
        1 : "馬上到達",
        2 : "已離開",
        3 : "到達"
    };
    for (var i = 0; i < data.length; i++) {
        var d = data[i];
        if (d.stationid == stationid) {
            continue
        }
        var a = $("#busdetail>table>tbody>tr[data-id=" + d.stationid + "]");
        var c = a ? a.find("td:eq(1)").text() : d.stationid;
        c = states[d.stationstate] + "<b>{0}</b>".format(c);
        sb.append('<tr data-id="{0}"><td class="hidden-xs">{1}</td><td>{2}</td><td>{3}</td><td class="hidden-xs">{4}</td><td class="hidden-xs">{5}</td><td>{6}</td></tr>'.format(d.carid, d.name, d.waittime, d.distance, d.lng, d.lat, c))
    }
    return b.html(sb.toString());
}
$(function() {
    $("form.navbar-form button").click(searchBus);
    window.document.body.onresize = bodyResize;
    $("#buslist").on("click", "table tr a",
    function() {
        var id = $(this).parents("tr").data("id");
        busid = id;
        $.getJSON("index.php/bus/line_detail/" + id,
        function(r) {
            if (r.ret == 0) {
                bus_show("busdetail",
                function(id) {
                    var e = $(id);
                    e.html(loadStation(r.data))
                })
            }
        })
    });
    $("#btnList").on("click",
    function() {
        $(this).parent().siblings().removeClass("active");
        $(this).parent().addClass("active");
        bus_show("buslist")
    });
	/**
	*查询附近的汽车。
	*/
    $("#busdetail").on("click", "table tr a",
    function() {
		var f = function() {
            $.getJSON("index.php/bus/near_cars/" + busid + "/" + stationid,
            function(r) {
                
                if (r.success) {
                    loadNearCars(r.data)
                }else{
					$("#busdetail div table tbody").empty();
				}
            })
        }
        var t = $(this).parents("tr");
        t.siblings("tr.detail").remove();
        var id = t.data("id");
        stationid = id;
        t.after('<tr class="detail" style="background-color: #77c5d5"><td colspan="5">{0}</td></tr>'.format('<div class="table-reponsive"><table class="table table-striped "><thead><tr>' + '<th class="hidden-xs">車牌號</th><th>預計時間(秒)</th><th>距離</th><th class="hidden-xs">經度</th><th class="hidden-xs">緯度</th><th>站臺</th></tr></thead>' + "<tbody></tbody></table></div> "));
        clearInterval(iIntval);
		f();
        iIntval = setInterval(f,10 * 1000);
		
    });
    $("#nearstation").on("click", "table tr a",
    function() {
        var aname = $(this).parent().siblings().eq(1).text();
        $.post("index.php/bus/get_lines_by_station", {
            name: aname
        },
        function(r) {
            if (r.ret == 0) {
                bus_show("buslist",
                function(id) {
                    $(id).html(loadBus(r.data))
                })
            }
        },
        "json")
    });
    $(".main-content").on("click", "button.toList",
    function() {
        bus_show("buslist")
    });
    $("#btnAll").on("click",
    function() {
        $("#busPagination").TSRC_Pagination({
            onGetCount: getLineCount,
            onGetPage: getLines,
            pagesize: 20
        })
    });
    bodyResize();
    $("#btnMystation").on("click",
    function() {
        $(this).parent().siblings().removeClass("active");
        $(this).parent().addClass("active");
        showTips("正在定位和查詢中，請稍候片刻……");
        GetGeo(function(pos) {
            var lat = pos.coords.latitude;
            var lng = pos.coords.longitude;
            my_pos = {
                "lat": lat,
                "lng": lng,
                "alt": pos.coords.altitude
            };
            $.getJSON("index.php/bus/near_station/" + lat + "/" + lng,
            function(r) {
                var t = typeof r;
                if (t == "string") {
                    r = JSON.parse(r)
                }
                if (r.success) {
                    bus_show("nearstation",
                    function(id) {
                        $(id).html(loadNearStation(r.data))
                    })
                }
            })
        })
    })
});